package com.mall.shopping.services;

import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlRenameTableStatement;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mall.shopping.IProductService;
import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.converter.ContentConverter;
import com.mall.shopping.converter.ProductConverter;
import com.mall.shopping.dal.entitys.Item;
import com.mall.shopping.dal.entitys.ItemDesc;
import com.mall.shopping.dal.entitys.Panel;
import com.mall.shopping.dal.entitys.PanelContentItem;
import com.mall.shopping.dal.persistence.ItemDescMapper;
import com.mall.shopping.dal.persistence.ItemMapper;
import com.mall.shopping.dal.persistence.PanelContentMapper;
import com.mall.shopping.dal.persistence.PanelMapper;
import com.mall.shopping.dto.*;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.entity.Example;

import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

/**
 * @Author tangjian
 * @Date 2021/10/31 13:44
 * @description
 */
@Service
public class ProductService implements IProductService {

    @Autowired
    ItemMapper itemMapper;
    @Autowired
    ItemDescMapper itemDescMapper;
    @Autowired
    ProductConverter productConverter;


    @Autowired
    PanelMapper panelMapper;

    @Autowired
    PanelContentMapper panelContentMapper;


    @Autowired
    ContentConverter contentConverter;


    @Override
    public ProductDetailResponse getProductDetail(ProductDetailRequest request) {

        ProductDetailResponse response = new ProductDetailResponse();

        try {
            Item item = itemMapper.selectByPrimaryKey(request.getId());
            ItemDesc itemDesc = itemDescMapper.selectByPrimaryKey(request.getId());

            ProductDetailDto productDetailDto = productConverter.productDO2DTO(item);
            productDetailDto.setProductImageSmall(Arrays.asList(item.getImages()));
            productDetailDto.setDetail(itemDesc.getItemDesc());

            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
            response.setProductDetailDto(productDetailDto);
        } catch (Exception e) {
            e.printStackTrace();
            response.setCode(ShoppingRetCode.DB_EXCEPTION.getCode());
            response.setMsg(ShoppingRetCode.DB_EXCEPTION.getMessage());
        }

        return response;
    }

    @Override
    public AllProductResponse getAllProduct(AllProductRequest request) {
        AllProductResponse response = new AllProductResponse();
        try {
            PageHelper.startPage(request.getPage(), request.getSize());
            Example example = new Example(MySqlRenameTableStatement.Item.class);
            example.createCriteria().andEqualTo("cid", request.getCid()).andBetween("price",request.getPriceLte(),request.getPriceGt());
            example.setOrderByClause("price" + " " + request.getSort());
            List<Item> items = itemMapper.selectByExample(example);
            PageInfo<Item> pageInfo = new PageInfo<>(items);

            List<ProductDto> productDtos = productConverter.items2Dto(items);


            response.setProductDtoList(productDtos);
            response.setTotal(pageInfo.getTotal());
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            response.setCode(ShoppingRetCode.DB_EXCEPTION.getCode());
            response.setMsg(ShoppingRetCode.DB_EXCEPTION.getMessage());
        }

        return response;
    }

    /**
     * 根据条件查询商品
     *
     * @param request
     * @return
     */
    @Override
    public AllProductResponse searchAllProduct(AllProductRequest request) {
        PageHelper.startPage(request.getPage(), request.getSize());
        //设置条件
        Example example = new Example(Item.class);
        Example.Criteria criteria = example.createCriteria();

        if (request.getKey() != null && !"".equals(request.getKey())) {
            criteria.andLike("title", "%" + request.getKey() + "%");
        }
        if (request.getPriceGt() != null) {
            criteria.andGreaterThanOrEqualTo("price", request.getPriceGt());
        }
        if (request.getPriceLte() != null) {
            criteria.andLessThanOrEqualTo("price", request.getPriceLte());
        }
        if (request.getCid() != null) {
            criteria.andEqualTo("cid", request.getCid());
        }
        //"”代表不排序，1代表价格从低到高，-1代表价格从高到低
        if (request.getSort() != null && !"".equals(request.getSort())) {
            //排序规则
            String order = "desc";

            if (1 == Integer.parseInt(request.getSort())) {
                order = "asc";
            }
            example.setOrderByClause("price " + order);
        }

        //执行
        List<Item> items = itemMapper.selectByExample(example);
        AllProductResponse response = new AllProductResponse();

        if (items != null && items.size() > 0) {
            //转换
            List<ProductDto> productDtos = productConverter.items2Dto(items);
            long total = new PageInfo<>(items).getTotal();
            response.setTotal(total);
            response.setProductDtoList(productDtos);
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
            return response;
        }
        //查询失败
        response.setCode(ShoppingRetCode.DB_EXCEPTION.getCode());
        response.setMsg("查询数据失败");
        return response;
    }

    /**
     * 推荐商品
     *
     * @return
     */
    @Override
    public RecommendResponse getRecommendGoods() {
        //查询remark为热门推荐的类目
        Example panelExample = new Example(Panel.class);
        panelExample.createCriteria().andLike("remark", "%热门推荐%");
        List<Panel> panels = panelMapper.selectByExample(panelExample);

        //接着查询热门推荐商品
        RecommendResponse response = new RecommendResponse();
        if (panels != null && panels.size() > 0) {
            Set<PanelDto> panelContentItemDtos = new LinkedHashSet<>();
            for (Panel panel : panels) {
                //遍历赋值
                //查找该类目id相关的商品
                List<PanelContentItem> panelContentItems = panelContentMapper.selectPanelContentAndProductWithPanelId(panel.getId());
                //转换
                List<PanelContentItemDto> panelContentItemDtoList = contentConverter.panelContentItem2Dto(panelContentItems);
                PanelDto panelDto = contentConverter.panen2Dto(panel);
                panelDto.setPanelContentItems(panelContentItemDtoList);
                //添加
                panelContentItemDtos.add(panelDto);
            }

            //查询成功
            response.setPanelContentItemDtos(panelContentItemDtos);
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            return response;
        }

        //查询失败
        response.setCode(ShoppingRetCode.DB_EXCEPTION.getCode());
        response.setMsg("查询数据失败");
        return response;
    }
}
